package com.zhiyou.app.config.ordertaskhandler;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.zhiyou.app.pojo.bo.TaskResult;
import com.zhiyou.app.service.ComfyUIService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class BaseOrderTaskHandler<T extends BaseOrderTaskHandler<T>> {
    protected ComfyUIService getComfyUIService() {
        return SpringUtil.getBean(ComfyUIService.class);
    }

    /**
     * 通过表达式路径为JSONObject设置值
     *
     * @param jsonObject 目标JSONObject
     * @param expression 表达式路径，如"2.inputs.children[1].name"
     * @param value      要设置的值
     * @return 修改后的JSONObject
     */
    protected JSONObject setValue(JSONObject jsonObject, String expression, Object value) {
        String[] parts = expression.split("\\.");
        Object current = jsonObject;

        // 遍历到倒数最后一个路径
        for (int i = 0; i < parts.length - 1; i++) {
            current = getObjectFromPath(current, parts[i]);
            if (current == null) {
                throw new IllegalArgumentException("无法在路径 '" + expression + "' 中找到元素: " + parts[i]);
            }
        }

        // 设置值
        setObjectValue(current, parts[parts.length - 1], value);
        return jsonObject;
    }

    /**
     * 通过多个表达式路径为JSONObject设置多个值
     *
     * @param jsonObject  目标JSONObject
     * @param expressions 表达式路径数组，如["2.inputs.children[1].name", "3.inputs.size"]
     * @param values      要设置的值数组，与表达式一一对应
     * @return 修改后的JSONObject
     */
    protected JSONObject setValues(JSONObject jsonObject, String[] expressions, Object[] values) {
        if (expressions.length != values.length) {
            throw new IllegalArgumentException("表达式数量与值数量不匹配");
        }
        for (int i = 0; i < expressions.length; i++) {
            setValue(jsonObject, expressions[i], values[i]);
        }
        return jsonObject;
    }

    /**
     * 根据路径部分获取对象
     *
     * @param current  当前对象
     * @param pathPart 路径部分，如 "inputs" 或 "children[1]"
     * @return 对应的对象
     */
    private Object getObjectFromPath(Object current, String pathPart) {
        // 解析数组索引，如 "children[1]"
        Pattern arrayPattern = Pattern.compile("(.*)\\[(\\d+)\\]$");
        Matcher matcher = arrayPattern.matcher(pathPart);

        String key;
        Integer index = null;

        if (matcher.matches()) {
            key = matcher.group(1);
            index = Integer.parseInt(matcher.group(2));
        } else {
            key = pathPart;
        }

        // 获取当前对象中的值
        Object obj = null;
        if (current instanceof com.alibaba.fastjson.JSONObject) {
            obj = ((com.alibaba.fastjson.JSONObject) current).get(key);
        } else if (current instanceof Map) {
            obj = ((Map) current).get(key);
        }

        // 如果有索引，则获取数组中的元素
        if (index != null && obj instanceof List) {
            List list = (List) obj;
            if (index < list.size()) {
                return list.get(index);
            } else {
                return null;
            }
        }

        return obj;
    }

    /**
     * 为对象设置值
     *
     * @param current  当前对象
     * @param pathPart 路径部分
     * @param value    要设置的值
     */
    private void setObjectValue(Object current, String pathPart, Object value) {
        // 解析数组索引，如 "children[1]"
        Pattern arrayPattern = Pattern.compile("(.*)\\[(\\d+)\\]$");
        Matcher matcher = arrayPattern.matcher(pathPart);

        if (matcher.matches()) {
            // 处理数组情况，如 "children[1]"
            String key = matcher.group(1);
            int index = Integer.parseInt(matcher.group(2));

            if (current instanceof com.alibaba.fastjson.JSONObject) {
                com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) current;
                Object obj = json.get(key);
                if (!(obj instanceof List)) {
                    List list = new ArrayList();
                    json.put(key, list);
                    obj = list;
                }
                List list = (List) obj;
                ensureListSize(list, index);
                list.set(index, value);
            } else if (current instanceof Map) {
                Map map = (Map) current;
                Object obj = map.get(key);
                if (!(obj instanceof List)) {
                    List list = new ArrayList();
                    map.put(key, list);
                    obj = list;
                }
                List list = (List) obj;
                ensureListSize(list, index);
                list.set(index, value);
            }
        } else {
            // 处理普通属性情况
            if (current instanceof com.alibaba.fastjson.JSONObject) {
                ((com.alibaba.fastjson.JSONObject) current).put(pathPart, value);
            } else if (current instanceof Map) {
                ((Map) current).put(pathPart, value);
            }
        }
    }

    /**
     * 确保List的大小至少为index+1
     *
     * @param list  List对象
     * @param index 索引
     */
    private void ensureListSize(List<?> list, int index) {
        while (list.size() <= index) {
            list.add(null);
        }
    }

    public abstract void postInitParam(String param);

    public abstract JSONObject parseWorkflow(JSONObject workFlow);

    public abstract TaskResult parseResult(Map<String, List<String>> result, Map<String, Object> config);

    protected abstract String getTaskType();

}
